package com.strategy.strategy.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.strategy.Abstract.AbstractUploadStrategyImpl;
import com.strategy.config.ObjectStoreProperties;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * ClassName:OssUploadStrategyImpl
 * Package:com.strategy.strategy.impl
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/7/16 - 22:16
 * @Version:v1.0
 */
@Slf4j
@Getter
@Setter
@RequiredArgsConstructor
@Service("ossUploadServiceImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {

    /**
     * 构造器注入bean
     */
    private final ObjectStoreProperties properties;

    /**
     * 当前类的属性
     */
    private OSS ossClient;

    //初始化ossClient对象
    @Override
    public void initClient() {
        ossClient = new OSSClientBuilder().build(properties.getOss().getEndpoint(), properties.getOss().getAccessKey(), properties.getOss().getSecretKey());
        log.info("OssClient Init Success...");
    }

    @Override
    public boolean checkFileIsExisted(String fileRelativePath) {
        return ossClient.doesObjectExist(properties.getOss().getBucketname(), fileRelativePath);
    }

    //阿里云文件上传逻辑
    @Override
    public String executeUpload(MultipartFile file) throws IOException {
        log.info("File Upload Starts...");
        // 获取文件原始名称
        String filename = file.getOriginalFilename();
        // 完善1、 --> 在文件名中添加唯一值
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + filename;
        // 完善2、 --> 把文件按照日期分类
        String datePath = new DateTime().toString("yyyy/MM/dd");
        // 拼接时间 yyyy/MM/dd/filename
        filename = datePath + "/" + filename;
        ossClient.putObject(properties.getOss().getBucketname(), filename, file.getInputStream());
        log.info("File Upload Finish...");
        return filename;
    }

    //返回文件访问公网地址
    @Override
    public String getPublicNetworkAccessUrl(String fileRelativePath) {
        String url = "https://"+properties.getOss().getBucketname()+"."+properties.getOss().getEndpoint()+"/"+fileRelativePath;
        return url;
    }
}

